import { useStore } from 'vuex'
import { ref, computed, ComputedRef } from 'vue'

// 加载参数
interface LoadParams {
  currentPage?: number;
  pageSize?: number;
  [key: string]: any;
}
const useLoadMore = (actionName: string, total: ComputedRef<number>,
  params: LoadParams = {}, pageSize = 5) => {
  // 定义变量
  const store = useStore()
  const currentPage = ref((params && params.currentPage) || 1)
  // 使用计算函数包裹对象，使对象属性是响应性的
  const requestParams = computed(() => {
    return {
      ...params,
      currentPage: currentPage.value + 1
    }
  })

  // 加载更多数据函数
  const loadMorePage = () => {
    store.dispatch(actionName, requestParams.value).then(() => {
      currentPage.value++
    })
  }
  // 判断是否最后一页
  const isLastPage = computed(() => {
    // Math.ceil: 返回大于等于这个数的整数
    return Math.ceil((total.value || 1) / pageSize) === currentPage.value
  })
  return {
    loadMorePage,
    isLastPage,
    currentPage
  }
}

export default useLoadMore
